package com.kexio.gen.config;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * JSON字符串反序列化器
 * 
 * 将前端传来的JSON对象自动转换为JSON字符串存储到数据库
 * 
 * @author 系统
 * @since 2025-09-16
 */
public class JsonStringDeserializer extends JsonDeserializer<String> {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Override
    public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        JsonToken token = p.getCurrentToken();
        
        // 如果是null
        if (token == JsonToken.VALUE_NULL) {
            return null;
        }
        
        // 如果已经是字符串，直接返回
        if (token == JsonToken.VALUE_STRING) {
            return p.getValueAsString();
        }
        
        // 如果是JSON对象或数组，转换为字符串
        if (token == JsonToken.START_OBJECT || token == JsonToken.START_ARRAY) {
            JsonNode node = p.readValueAsTree();
            return OBJECT_MAPPER.writeValueAsString(node);
        }
        
        // 其他类型转换为字符串
        return p.getValueAsString();
    }
}

